package chordcows;
import java.net.*;
import java.io.*;

/**
 *
 * @author chris day
 * @project everyonesBOX
 */
public class TransferClient {

	public static Boolean download(String directory, String filename, String[][] servers) {
		int bytesread;
		int filesize = 8192;
		InetAddress ip=null;
		for(int i = 0; i < servers[0].length; i++) {
			
			
			try {
				ip=InetAddress.getByName(servers[0][i]);
				System.out.println("Connecting to "+ ip.getHostAddress()+ " "+Integer.parseInt(servers[1][i]));
				Socket servsock = new Socket(ip, Integer.parseInt(servers[1][i]));
				

				byte[] bytearray = new byte[filesize];
				PrintStream transmitter = new PrintStream(servsock.getOutputStream());
				InputStream receiver = servsock.getInputStream();
				BufferedReader inputreader = new BufferedReader(new InputStreamReader(receiver));

				System.out.println("Sending filename...");
				transmitter.println(filename);
				transmitter.flush();
				String result = inputreader.readLine();

				System.out.println("Received response...");
				if(result.equals("true")) {
					System.out.println("Sending ack...");
					System.out.println("Writing file...");
					BufferedOutputStream fileoutput = new BufferedOutputStream(new FileOutputStream(directory +"/"+ filename));
					transmitter.println("ack");
					transmitter.flush();
					
				    while((bytesread = receiver.read(bytearray)) != -1) {
						fileoutput.write(bytearray, 0, bytesread);
						fileoutput.flush();
					}

					fileoutput.close();
					servsock.close();

					System.out.println("Finished...");
					return true;
				} else {
					System.out.println("Failed to download file from " + ip + "...");
				}

				servsock.close();
			} catch (UnknownHostException ex) {
				System.err.println(ex);
			} catch (IOException ex) {
				System.err.println("Unable to connect to server: " + ex);
			}
		}

		return false;
	}
}
